package org.ohuang

import com.google.gson.Gson
import org.ohuang.bean.ApkBean
import org.ohuang.bean.ChannelBean
import java.io.File

/**
 * 打渠道号
 */
object ChannelUtil {


    fun outConfig(file: File){
        var gson = Gson()
        var apkBean = ChannelBean()
        var arrayList = ArrayList<String>()
        arrayList.add("渠道1")
        arrayList.add("渠道2")
        apkBean.channel=arrayList
        var fromJson = gson.toJson(apkBean)
        writeText(file, fromJson)
    }

     fun start(apkTool:String,javaexe: String?, apksigner: String,zipalign: String,jsonPath:String){
         var file = File(jsonPath)
         var gson = Gson()
         var readText = readText(file)
         var fromJson: ChannelBean = ChannelBean()
         tryCatch("${file.name} 内容不符合json格式") {
             fromJson = gson.fromJson(readText, ChannelBean::class.java)
         }
         var rootPath1 = file.parentFile.absolutePath + "/"
         setAbsolutePath(fromJson,rootPath1)

         var dirPath= removeSuffix(fromJson.apkPath,".apk")
         var file1 = File(dirPath)
         if (file1.exists()){
             file1.delete()
         }
//         ZipUtil.unzip(fromJson.apkPath,dirPath)
         apkEncode(javaexe,apkTool,fromJson.apkPath,dirPath)
         fromJson.channel.forEach {
             println("--- ${it}  开始打包")
             writeChanel(it,fromJson,dirPath)
             var tempApkPath= "$rootPath1/build/temp.apk"
//             ZipUtil.toZip(tempApkPath,dirPath,true)
             toApk(javaexe,apkTool,dirPath,tempApkPath)
             var outPath= "$rootPath1/build/out.apk"
             toZipalign(tempApkPath,outPath,zipalign)
             toSigner(javaexe,apksigner,outPath,it,fromJson)
//             File(tempApkPath).delete()
             println("--- ${it}  打包完成")
         }

     }

    private fun apkEncode(javaexe: String?, apktool: String, apkPath: String,dirPath:String) {
        println("开始反编译")
        var file = File(dirPath)
        if (file.exists()) {
            println("删除文件${file.name}")
            var delete = FileUtils.delete(file)
            if (delete) {
                println("删除成功")
            } else {
                println("删除失败")
            }
        }
        var java: String = if (javaexe.isNullOrEmpty()) {
            "java"
        } else {
            javaexe.replace(" ", "\" \"")
        }
        val cmd =
            "$java -Dfile.encoding=utf-8 -jar  \"$apktool\" d  \"$apkPath\"  -o \"${dirPath}\" -f --no-res --no-src"
        println(cmd)
        var arrayOf = arrayOf(
            "cmd.exe", "/c", cmd
        )

        var exec = ExecUtil.execAndPrint(
            arrayOf,
            30 * 60
        )
        println(exec)

    }

    private fun toApk(javaexe: String?, apktool: String,dirPath:String,outPath: String) {
        println("开始生成apk")
        var file = File(outPath)
        if (file.exists()) {
            println("删除文件${file.name}")
            var delete = file.delete()
            if (delete) {
                println("删除成功")
            } else {
                println("删除失败")
            }
        }
        var java = if (javaexe.isNullOrEmpty()) {
            "java"
        } else {
            javaexe.replace(" ", "\" \"")
        }


        val cmd =
            "$java -Dfile.encoding=utf-8 -jar \"$apktool\" b \"${dirPath}\" -o \"${file.absolutePath}\""
        println(cmd)
        var execAndPrint = ExecUtil.execAndPrint(arrayOf("cmd.exe", "/c", cmd), 30 * 60)


        println(execAndPrint)
    }

    private fun toZipalign(tempApkPath:String,outPath:String, zipalign: String) {
        println("开始资源文件对齐")
        var file = File(outPath)
        if (file.exists()) {
            println("删除文件${file.name}")
            var delete = file.delete()
            if (delete) {
                println("删除成功")
            } else {
                println("删除失败")
            }
        }
        val cmd =
            "${zipalign.replace(" ", "\" \"")}  -p -f -v 4 \"${tempApkPath}\"  \"${file.absolutePath}\""
        println(cmd)
        var arrycmd = arrayOf("cmd.exe", "/c", cmd)
        var exec = ExecUtil.execAndPrint(
            arrycmd,
            10 * 60, "Verification succesful"
        )
        println(exec)
    }

    private fun writeChanel(channel: String,channelBean: ChannelBean,dirPath:String){
        var path=dirPath+"/assets"+channelBean.channelPath
        var file = File(path)
        writeText(file,channel)
    }

    private fun setAbsolutePath(fromJson: ChannelBean, rootPath: String) {
        var rootPath1=rootPath;
        if (rootPath.endsWith("/")||rootPath.endsWith("\\")){

        }else{
            rootPath1= "$rootPath/"
        }
        if (fromJson.apkPath.isNotEmpty() && !fromJson.apkPath.contains(":")) {//如果不是绝对路径
            fromJson.apkPath = rootPath1 + fromJson.apkPath
        }

        if (fromJson.signingPath.isNotEmpty() && !fromJson.signingPath.contains(":")) {
            fromJson.signingPath = rootPath1 + fromJson.signingPath
        }
    }

    private fun toSigner(javaexe: String?, apksigner: String, apkPath: String,channel:String, channelBean: ChannelBean) {
        println("开始签名")
        var subSequence = removeSuffix(apkPath,".apk")
        var file = File("$subSequence-${channel}.apk")
        if (file.exists()) {
            println("删除文件${file.name}")
            var delete = file.delete()
            if (delete) {
                println("删除成功")
            } else {
                println("删除失败")
            }
        }
        var java: String = if (javaexe.isNullOrEmpty()) {
            "java"
        } else {
            javaexe.replace(" ", "\" \"")
        }


        val cmd =
            "$java -Dfile.encoding=utf-8 -jar  \"$apksigner\" sign  --in  \"${apkPath}\"  " +
                    "--out \"${file.absolutePath}\" --v1-signing-enabled true --v2-signing-enabled true --v3-signing-enabled true --ks  " +
                    "\"${channelBean.signingPath}\"  --ks-pass pass:\"${channelBean.keyPassword}\" --ks-key-alias \"${channelBean.keyAlias}\""
        println(cmd)
        var execAndPrint = ExecUtil.execAndPrint(
            arrayOf(
                "cmd.exe", "/c", cmd
            ),
            30 * 60
        )
        println(execAndPrint)
    }


    private fun removeSuffix(s: String, suffix: String): String {
        var substringAfter = s.lastIndexOf(suffix)
        var subSequence = s.subSequence(0, substringAfter)
        return subSequence.toString()
    }
}